package com.yanqu.road.server.manger.activity.orewar;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.battle.BattleResult;
import com.yanqu.road.entity.config.skill.SkillInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.orewar.*;
import com.yanqu.road.entity.player.*;
import com.yanqu.road.entity.task.args.OreWarActivityUnionRiseRankArgs;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.logic.bussiness.player.UserBeautyBussiness;
import com.yanqu.road.logic.bussiness.player.UserOreWarBussiness;
import com.yanqu.road.logic.bussiness.player.UserPatronsBussiness;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.BattlePb;
import com.yanqu.road.logic.pb.PatronsPb;
import com.yanqu.road.logic.thread.ThreadTaskManger;
import com.yanqu.road.pb.orewar.OreWarProto;
import com.yanqu.road.pb.patrons.PatronsProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.BeautyModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.OreWarModule;
import com.yanqu.road.server.logic.battle.BattleManager;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.config.SkillMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.WorldMessageMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.pb.OreWarPb;
import com.yanqu.road.server.pb.WorldMessagePb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.UUIDHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.executor.GeneralTask;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class OreWar{

	private Logger logger = LogManager.getLogger(OreWar.class.getName());

	private final Object lockObj = new Object();

	private ActivityInfo activityInfo;

	private Map<Integer, OreStationInfo> oreStationMap;

	private OreStationInfo firstOreStationInfo;

	private Map<Integer, OrePitInfo> orePitInfoMap;

	private ThreadTaskManger threadTaskManger;

	private AtomicInteger actionId = new AtomicInteger(1);

	private Map<Integer, UserOrePit> userOrePitMap;//用户坑位信息

	private Map<Long, List<OreWarRecord>> oreWarRecordMap;//战斗记录

	private LinkedList<OreWarNotice> oreWarNoticeList;

	private List<OreWarNotice> needAddNoticeList;

	private List<OreWarRecord> needAddRecordList = new ArrayList<>();

	private List<UserOrePit> needUpdateUserOrePitList = new ArrayList<>();

	private RandomHelper random = new RandomHelper();

	private long blowoutTime = 0;//井喷的触发时间点

	private boolean isReload = false;//在重启或者刷新的时候不会对冠名的变化产生影响，启动的时候会导致冠名在对象中从无到有，会触发冠名奖励

	public OreWar(ActivityInfo acInfo){
		activityInfo = acInfo;
//		reload();
	}

	/**
	 * 出现维护一天以上的跨天维护时，首先先发昨天的奖励，发完奖励后去掉坑位的井喷状态，然后再次井喷
	 */
	public void timerTask(){
		long nowTimeMilli = System.currentTimeMillis();
		systemRecall(nowTimeMilli);//先判断是否要撤回玩家发放奖励
		stopBlowoutStation(nowTimeMilli,false);//顺序不能乱，先发奖励再消失井喷
		randomBlowoutStation(nowTimeMilli);//顺序不能乱，先判断要不要停止井喷，再开始新的井喷
	}

	public boolean init() {
		return reload();
	}

	public boolean stop() {
		return false;
	}

	public boolean save() {
		List<UserOrePit> tempPitList;
		synchronized (needUpdateUserOrePitList) {
			tempPitList = new ArrayList<>(needUpdateUserOrePitList);
			needUpdateUserOrePitList = new ArrayList<>();
		}
		if (tempPitList.size() > 0) {
			UserOreWarBussiness.updateUserOrePitList(tempPitList);
		}
		//保存记录
		List<OreWarRecord> tempNeedAddRecord;
		synchronized (needAddRecordList) {
			tempNeedAddRecord = new ArrayList<>(needAddRecordList);
			needAddRecordList = new ArrayList<>();
		}
		if (tempNeedAddRecord.size() > 0) {
			UserOreWarBussiness.addOreWarRecordList(tempNeedAddRecord);
		}
		List<OreWarNotice> tempNeedAddNotice = new ArrayList<>();
		synchronized (needAddNoticeList){
			tempNeedAddNotice.addAll(needAddNoticeList);
			needAddNoticeList = new ArrayList<>();
		}
		if(tempNeedAddNotice.size() > 0){
			UserOreWarBussiness.addOreWarNoticeList(tempNeedAddNotice);
		}
		return true;
	}

	public ActivityInfo getActivityInfo(){
		return activityInfo;
	}

	public boolean reload() {
		isReload = true;
		oreStationMap = ActivityBussiness.getOreWarStationInfoMap(activityInfo.getActivityId());
		if (oreStationMap.size() <= 0) {
			return false;
		}
		orePitInfoMap = initOrePitMap();
		if(orePitInfoMap.size() <= 0){
			return false;
		}

		threadTaskManger = new ThreadTaskManger(4, "oreWarTaskManger");
		userOrePitMap = UserOreWarBussiness.getUserOrePitMap(activityInfo.getActivityId());
		boolean isChange = false;
		if(userOrePitMap.size() < orePitInfoMap.size()){
			UserOreWarBussiness.initUserOrePitMap(orePitInfoMap, userOrePitMap);
			isChange = true;
		}
		if(isChange){
			userOrePitMap = UserOreWarBussiness.getUserOrePitMap(activityInfo.getActivityId());
		}

		refreshOreStation();
		//加载记录信息
		oreWarRecordMap = UserOreWarBussiness.getOreWarRecordMap(activityInfo.getActivityId());
		needAddRecordList = new ArrayList<>();
		//加载通告信息
		oreWarNoticeList = UserOreWarBussiness.getOreWarNoticeList(activityInfo.getActivityId(),GameConfig.MINE_WAR_MAX_NOTICE_COUNT);
		needAddNoticeList = new ArrayList<>();

		isReload = false;
		return true;
	}



	//根据坑位信息，返回随机权重中的一个坑位
	private int randomWeightBlowout(List<Integer> stationIdList){
		int randomStationId = 0;
		int allWeight = 0;
		for(Integer stationId : stationIdList){
			allWeight += oreStationMap.get(stationId).getBlowoutWeight();
		}
		int randomValue = random.next(0,allWeight);
		for(Integer stationId : stationIdList){
			if(randomValue < oreStationMap.get(stationId).getBlowoutWeight()){
				randomStationId = stationId;
				break;
			}
			randomValue = randomValue - oreStationMap.get(stationId).getBlowoutWeight();

		}
		return randomStationId;
	}

	//随机井喷资源点
	private void randomBlowoutStation(long nowTimeMilli){
		List<Integer> blowoutList = new ArrayList<>();
		boolean checkIsBlowout = false;
		if(DateHelper.getZeroTimeStamp(blowoutTime) != DateHelper.getZeroTimeStamp(nowTimeMilli)){
			List<Integer> blowoutParamList = StringUtils.stringToIntegerList(activityInfo.getParam4(),"\\|");
			long startMinute = blowoutParamList.get(0);
			int blowoutNum = blowoutParamList.get(1);
			if(nowTimeMilli >= DateHelper.getZeroTimeStamp(nowTimeMilli) + startMinute * 60 * 1000){
				List<Integer> tempList = new ArrayList<>();
				for(int stationId : oreStationMap.keySet()){
					tempList.add(stationId);
					if(oreStationMap.get(stationId).isBlowout()){
						checkIsBlowout = true;
					}
				}
				if(!checkIsBlowout){
					//没有权重版本
					/*for(int i = 0;i<blowoutNum;i++){
						int randomIndex = random.next(0,tempList.size());
						int stationId = tempList.get(randomIndex);
						blowoutList.add(stationId);
						tempList.remove(randomIndex);
					}*/
					for(int i = 0;i<blowoutNum;i++){
						int randomStationId = randomWeightBlowout(tempList);
						blowoutList.add(randomStationId);
						tempList.remove(new Integer(randomStationId));
					}
					if(OreWarActivityMgr.getInTimeActivityInfo(activityInfo.getActivityId()) != null){
						WorldMessageMgr.worldNotify(eMessageType.OreWarBlowout.getValue());
					}
				}
				blowoutTime = nowTimeMilli;
			}
			if(blowoutList.size() > 0){
				//所有坑位先清除井喷状态
				for(UserOrePit userOrePit : userOrePitMap.values()){
					userOrePit.setBlowout(false);
				}
				//井喷之前先结算没有井喷前的奖励
				blowoutStartReward(blowoutList);
				for (Integer stationId : blowoutList){
					for(UserOrePit userOrePit : userOrePitMap.values()){
						if(userOrePit.getStationId() == stationId){
							userOrePit.setBlowout(true);
							synchronized (needUpdateUserOrePitList) {
								if (!needUpdateUserOrePitList.contains(userOrePit)) {
									needUpdateUserOrePitList.add(userOrePit);
								}
							}
						}
					}
				}
			}
			refreshOreStation();
		}
	}


	/**
	 * 	//结束井喷
	 * @param force boolean 强制结束，判断要撤回的时候会强制结束，有可能维护了一天导致还是在井喷时间内，通过坑位的玩家加入时间来判断井喷，理论上不可能出现坑上都没人的情况
	 */
	private void stopBlowoutStation(long nowTimeMilli ,boolean force){
		List<Integer> blowoutParamList = StringUtils.stringToIntegerList(activityInfo.getParam4(),"\\|");//开始井喷的时间分钟|井喷的个数
		long startBlowoutMinute = blowoutParamList.get(0);
		long startBlowoutTime = DateHelper.getZeroTimeStamp(nowTimeMilli) + startBlowoutMinute * 60 * 1000;
		List<Integer> acList = StringUtils.stringToIntegerList(activityInfo.getParam6(),"\\|");//活动开始在当天的分钟|活动结束在当天的分钟
		long endDayMinute = acList.get(1);
		long endDayTime = DateHelper.getZeroTimeStamp(nowTimeMilli) + endDayMinute * 60 * 1000;
		if(nowTimeMilli < startBlowoutTime || nowTimeMilli > endDayTime || force){
			for(UserOrePit userOrePit : userOrePitMap.values()){
				userOrePit.setBlowout(false);
				synchronized (needUpdateUserOrePitList) {
					if (!needUpdateUserOrePitList.contains(userOrePit)) {
						needUpdateUserOrePitList.add(userOrePit);
					}
				}
			}
			refreshOreStation();
		}
	}

	//刷新坑位信息
	public void refreshOreStation(){
		for(OreStationInfo oreStationInfo : getOreStationMap().values()){
			changeOreStation(oreStationInfo);
		}
	}


	public void patronsAbilityChange(GamePlayer player, int pitId, UserPatrons userPatrons) {
		UserOrePit userOrePit = getUserOrePit(pitId);
		if(null == userOrePit || userOrePit.getUserId() != player.getUserId()){
			return;
		}
		userOrePit.setNickName(player.getUserInfo().getNickName());//更新基础信息
		userOrePit.setDecoration(UserMgr.getDecoration(player.getUserId()));
		userOrePit.replacePatrons(userPatrons);
		//更新能力
		userOrePit.setTotalAbility(player.getModule(PatronsModule.class).getPatronsListAbility(userOrePit.getPatronsIdList()));
		OreStationInfo oreStationInfo = getOreStationInfo(userOrePit.getStationId());
		changeOreStation(oreStationInfo);
	}

	public OreWarProto.OreWarNoticeListMsg.Builder getUserOreWarNotice(GamePlayer player){
		List<OreWarNotice> cOreWarNoticeList = new ArrayList<>(oreWarNoticeList);
		List<OreWarNotice> resOreWarNoticeList = new ArrayList<>();
		for(OreWarNotice oreWarNotice : cOreWarNoticeList){
			if(!StringUtils.isNullOrEmpty(oreWarNotice.getEnemyBaseInfo().getUnionUid()) &&
					oreWarNotice.getEnemyBaseInfo().getUnionUid().equals(player.getUserInfo().getUnionUid())){
				resOreWarNoticeList.add(oreWarNotice);
			}else if(getOreStationInfo(getOrePitInfo(oreWarNotice.getPitId()).getStationId()).isNotice()){
				resOreWarNoticeList.add(oreWarNotice);
			}
		}
		OreWarProto.OreWarNoticeListMsg.Builder msg = OreWarPb.parseOreWarNoticeListMsg(resOreWarNoticeList);
		return msg;
	}

	/**
	 * 对手是否在来访记录中
	 */
	public boolean isInOreWarRecord(long userId, long enemyUserId){
		List<OreWarRecord> recordList = getUserOreWarRecord(userId);
		if(null == recordList){
			return false;
		}
		return recordList.stream().anyMatch(oreWarRecord -> oreWarRecord.getEnemyUserId() == enemyUserId);
	}

	/**
	 * 获取矿战来访记录
	 */
	public List<OreWarRecord> getUserOreWarRecord(long userId){
		return oreWarRecordMap.get(userId);
	}

	//撤回玩家的坑位
	public OreWarProto.OrePitWithdrawRespMsg.Builder orePitRecall(GamePlayer player, int pitId){
		OreWarProto.OrePitWithdrawRespMsg.Builder msg = OreWarProto.OrePitWithdrawRespMsg.newBuilder();
		Property occupyReward;
		UserOrePit userOrePit;
		long lastGetRewardTime;
		long nowTime = System.currentTimeMillis() / 1000;
		synchronized (lockObj) {
			userOrePit = getUserOrePit(pitId);
			if (null == userOrePit) {
				msg.setRet(GameErrorCode.E_ORE_WAR_ORE_PIT_NO_FOUND);
				return msg;
			}
			if(userOrePit.getUserId() != player.getUserId()){
				msg.setRet(GameErrorCode.E_MINE_WAR_MINE_PIT_OWNER_CHANGE);
				return msg;
			}
			//计算占领收益
			lastGetRewardTime = userOrePit.getLastGetRewardTime();
			occupyReward = getPitOccupyReward(player.getUserId(), userOrePit, nowTime, true);
			//清除状态
			clearOrePitUser(userOrePit);
		}
		//收益入袋
		player.getModule(CurrencyModule.class).addCurrency(occupyReward, eLogMoneyType.OreWar, eLogMoneyType.OreWarPitRecall);
		OreWarActivityMgr.conditionNotify(player.getUserId(),eGamePlayerEventType.OreWarAcCoinOutPut.getValue(),
				new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, occupyReward.getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID),
						player.getUserInfo().getUnionUid(), activityInfo.getActivityId()));
		LogMgr.addLogOreWarReward(player.getUserId(), activityInfo.getActivityId(), pitId, PropertyHelper.parsePropertyToString(occupyReward), nowTime - lastGetRewardTime,
				false, eLogMoneyType.OreWarPitRecall.getValue());
		player.getModule(OreWarModule.class).syncOrePit(userOrePit, true);
		//矿场资源
		int goodsId = GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID;
		msg.setRet(0);
		msg.setReward(occupyReward.getCountByGoodsId(goodsId).intValue());
		return msg;
	}

	//活动的每日激活时间
	public boolean isActivityActive(){
		List<Integer> acList = StringUtils.stringToIntegerList(activityInfo.getParam6(),"\\|");//活动开始在当天的分钟|活动结束在当天的分钟
		long startMinute = acList.get(0);
		long endMinute = acList.get(1);
		if(System.currentTimeMillis() < DateHelper.getTodayZeroTimeStamp() + startMinute*60*1000
				|| System.currentTimeMillis() > DateHelper.getTodayZeroTimeStamp() + endMinute*60*1000){
			return false;
		}
		return true;
	}

	public void systemRecall(long nowTimeMilli){
		List<Integer> acList = StringUtils.stringToIntegerList(activityInfo.getParam6(),"\\|");//活动开始在当天的分钟|活动结束在当天的分钟
		long toadyZeroTime = DateHelper.getZeroTimeStamp(nowTimeMilli)/1000;
		long startSec = acList.get(0) * 60 + toadyZeroTime;
		long endSec = acList.get(1) * 60 + toadyZeroTime;
		long nowTime = nowTimeMilli/1000;
		long targetTime = 0;//以这个作为基准时间来判断加入多少时间的需要撤回，考虑到更新服务器停服一天的情况导致过了休战期
		if(nowTime >= startSec){
			targetTime = startSec;
		}
		if(nowTime >= endSec){
			targetTime = endSec;
		}
		//按照人头进行撤回
		List<Long> userIdList = new ArrayList<>();
		for(UserOrePit userOrePit : userOrePitMap.values()){
			//加入时间不对就是要撤回的
			if(userOrePit.getJoinTime() <= targetTime && userOrePit.getUserId() != 0 && !userIdList.contains(userOrePit.getUserId())){
				userIdList.add(userOrePit.getUserId());
			}
		}
		List<Long> userRefugeList = UserOreWarBussiness.getNeedRecallRefugeUserList(activityInfo.getActivityId(),targetTime);
		for(long userId : userRefugeList){
			if(!userIdList.contains(userId)){
				userIdList.add(userId);
			}
		}
		boolean isRecall = false;
		if(userIdList.size() > 0){
			isRecall = true;
		}
		for(long userId : userIdList){
			if(userId != 0){
				systemOrePitRecall(userId,nowTimeMilli);
				GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
				if(player != null){
					player.sendPacket(Protocol.U_ORE_WAR_MY_PIT_LIST, OreWarPb.parseMyOrePitListMsg(activityInfo.getActivityId(),new ArrayList<>(), false));
				}
			}
		}
		//监测到要撤回就一定要停止当前的井喷状态
		if(isRecall){
			stopBlowoutStation(nowTimeMilli,true);
		}
	}

	//系统撤回玩家坑位(包括争霸坑位和避难所的坑位)
	private void systemOrePitRecall(long userId,long nowTimeMilli){
		if(userId == 0){
			return;
		}
		Property systemRecallReward = new Property();
		long nowTime = nowTimeMilli / 1000;
		synchronized (lockObj) {
			for(UserOrePit userOrePit : userOrePitMap.values()){
				if(userOrePit.getUserId() == userId){
					//计算占领收益
					long lastGetRewardTime = userOrePit.getLastGetRewardTime();
					Property tempReward = getPitOccupyReward(userId, userOrePit, nowTime, true);
					systemRecallReward.addProperty(tempReward);
					//清除状态
					clearOrePitUser(userOrePit);
					LogMgr.addLogOreWarReward(userId, userOrePit.getActivityId(), userOrePit.getPitId(), PropertyHelper.parsePropertyToString(tempReward),
							nowTime - lastGetRewardTime, false, eLogMoneyType.OreWarPitRecall.getValue());
				}
			}
		}
		//撤回广场的坑位
		systemRecallReward.addProperty(getRefugeSystemRecallAll(userId,nowTimeMilli));
		if(!systemRecallReward.isNothing()){
			// 给每日自动撤回的玩家发送邮件和占领奖励
			UserInfo recallUser = UserMgr.getUserInfo(userId);
			String mailTitle = MultipleLanguageMgr.getContent(MailManager.ACTIVITY_ORE_WAR_TIMEOVER_TITLE, recallUser.getLanguage());
			String mailContent = MultipleLanguageMgr.getContent(MailManager.ACTIVITY_ORE_WAR_TIMEOVER_CONTENT, recallUser.getLanguage());
			MailManager.sendMail(userId, eMailType.DAILY.getValue(), PropertyHelper.parsePropertyToString(systemRecallReward), mailContent, mailTitle);

			OreWarActivityMgr.conditionNotify(userId,eGamePlayerEventType.OreWarAcCoinOutPut.getValue(),
					new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, systemRecallReward.getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID),
							recallUser.getUnionUid(), activityInfo.getActivityId()));
		}
	}

	//井喷之前要之前的奖励结算给玩家然后再开始井喷
	private void blowoutStartReward(List<Integer> stationIdList){
		long nowTime = System.currentTimeMillis()/1000;
		synchronized (lockObj) {
			for(UserOrePit userOrePit : userOrePitMap.values()){
				if(stationIdList.contains(userOrePit.getStationId()) && userOrePit.getUserId() != 0){
					//计算占领收益
					Property tempReward = getPitOccupyReward(userOrePit.getUserId(), userOrePit, nowTime, true);
					if(!tempReward.isNothing()){
						// 给每日开始井喷的据点上的用户发送没有井喷前的奖励
						UserInfo recallUser = UserMgr.getUserInfo(userOrePit.getUserId());
						String mailTitle = MultipleLanguageMgr.getContent(MailManager.ACTIVITY_ORE_WAR_BLOWOUT_TITLE, recallUser.getLanguage());
						String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.ACTIVITY_ORE_WAR_BLOWOUT_CONTENT, recallUser.getLanguage())
								,getOrePitName(userOrePit.getPitId(), recallUser.getLanguage()));
						MailManager.sendMail(userOrePit.getUserId(), eMailType.DAILY.getValue(), PropertyHelper.parsePropertyToString(tempReward), mailContent, mailTitle);

						OreWarActivityMgr.conditionNotify(userOrePit.getUserId(),eGamePlayerEventType.OreWarAcCoinOutPut.getValue(),
								new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, tempReward.getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID),
										recallUser.getUnionUid(), activityInfo.getActivityId()));
					}
					//同步坑位的领奖時間给客户端
					GamePlayer player = GamePlayerMgr.getOnlinePlayer(userOrePit.getUserId());
					if(player != null){
						player.getModule(OreWarModule.class).syncOrePit(userOrePit, false);
					}
				}
			}
		}

	}

	/**
	 * 清除矿坑占有状态
	 * @param userOrePit
	 */
	private void clearOrePitUser(UserOrePit userOrePit) {
		if (null == userOrePit) {
			return;
		}
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userOrePit.getUserId());
		updateOrePitPatronsState(player, userOrePit, OreWarMgr.DISPATCH_ORE_NONE);
		userOrePit.setActivityId(activityInfo.getActivityId());
		userOrePit.setUserId(0);
		userOrePit.setNickName("");
		userOrePit.setUnionName("");
		userOrePit.setDecoration("");
		userOrePit.setTotalAbility(BigInteger.ZERO);
		userOrePit.setLastGetRewardTime(System.currentTimeMillis() / 1000);
		userOrePit.setPatronsIdList(new ArrayList<>());
		userOrePit.setPatronsList(new ArrayList<>());
		synchronized (needUpdateUserOrePitList) {
			if (!needUpdateUserOrePitList.contains(userOrePit)) {
				needUpdateUserOrePitList.add(userOrePit);
			}
		}
		OreStationInfo stationInfo = getOreStationInfo(userOrePit.getStationId());
		if(null != stationInfo){
			changeOreStation(stationInfo);
		}
	}

	//返回用户的坑位信息????
	public List<UserOrePit> getUserOrePitList(int startPitId, int endPitId){
		List<UserOrePit> pitList = new ArrayList<>();
		if(null != userOrePitMap){
			for(int i = startPitId; i <= endPitId; i++){
				pitList.add(userOrePitMap.get(i));
			}
		}
		return pitList;
	}

	public List<UserOrePit> getUserOrePitList(long userId){
		List<UserOrePit> pitList = new ArrayList<>();
		for(UserOrePit userOrePit : userOrePitMap.values()){
			if(userOrePit.getUserId() == userId){
				pitList.add(userOrePit);
			}
		}
		return pitList;
	}

	private List<UserOrePit> getUserOrePitList(int stationId){
		List<UserOrePit> pitList = new ArrayList<>();
		for(UserOrePit userOrePit : userOrePitMap.values()){
			if(userOrePit.getStationId() == stationId){
				pitList.add(userOrePit);
			}
		}
		return pitList;
	}

	public UserOrePit getUserOrePit(int pitId){
		return userOrePitMap.get(pitId);
	}

	public Map<Integer, OreStationInfo> getOreStationMap() {
		return oreStationMap;
	}

	public OreStationInfo getOreStationInfo(int oreStationId){
		if(oreStationMap.containsKey(oreStationId)){
			return oreStationMap.get(oreStationId);
		}
		return null;
	}

	public Map<Integer, OrePitInfo> getOrePitInfoMap() {
		return orePitInfoMap;
	}

	public OrePitInfo getOrePitInfo(int pitId) {
		if(orePitInfoMap.containsKey(pitId)){
			return orePitInfoMap.get(pitId);
		}
		return null;
	}

	/**
	 * 按照ID规则生成矿坑地图信息
	 */
	private Map<Integer, OrePitInfo> initOrePitMap() {
		Map<Integer, OrePitInfo> totalOrePitInfoMap = new ConcurrentHashMap<>();
		int pitId = 1;
		int minStationId = Integer.MAX_VALUE;
		for(OreStationInfo stationInfo : getOreStationMap().values()){
			if(stationInfo.getStationId() < minStationId)minStationId = stationInfo.getStationId();
			for (int index = 0; index < stationInfo.getPitCount(); index++) {
				OrePitInfo pitInfo = new OrePitInfo();
				pitInfo.setActivityId(stationInfo.getActivityId());
				pitInfo.setName(stationInfo.getStationName());
				pitInfo.setStationId(stationInfo.getStationId());
				pitInfo.setPitId(pitId);
				pitInfo.setPitIndex(index + 1);
				pitInfo.setOutputSpeedAddition(stationInfo.getOutputSpeedAddition() + stationInfo.getAddOutputSpeedAddition() * (stationInfo.getPitCount() - index - 1));
				pitId++;
				totalOrePitInfoMap.put(pitInfo.getPitId(), pitInfo);
			}
		}
		firstOreStationInfo = getOreStationMap().get(minStationId);
		return totalOrePitInfoMap;
	}

	//返回第一个建筑的所有坑位信息
	public List<UserOrePit> getTopBuildingOrePitList(){
		List<UserOrePit> res = new ArrayList<>();
		for(int index = 1;index <= firstOreStationInfo.getPitCount();index ++){
			res.add(userOrePitMap.get(index));
		}
		return res;
	}

	public String getOrePitName(int pitId, String language){
		OrePitInfo pitInfo = getOrePitInfo(pitId);
		if(null == pitInfo){
			return "";
		}
		OreStationInfo stationInfo = getOreStationInfo(pitInfo.getStationId());
		if(null == stationInfo){
			return "";
		}
		return StringUtils.format(MultipleLanguageMgr.getContent(stationInfo.getStationName(), language), stationInfo.getShowStationIndex()) + "#" + pitInfo.getPitIndex();
	}

	//不包含#多少的部分
	public String getOreStationName(int stationId, String language){
		OreStationInfo stationInfo = getOreStationInfo(stationId);
		if(null == stationInfo){
			return "";
		}
		return StringUtils.format(MultipleLanguageMgr.getContent(stationInfo.getStationName(), language), stationInfo.getShowStationIndex());
	}

	public BigDecimal getOreOutput(long userId,List<UserPatrons> patronsList, int oreAddition,int unionAddition){
		if(null == patronsList){
			return BigDecimal.ZERO;
		}
		double skillAddition;
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
		Map<Integer, UserBeauty> beautyMap;
		if(null != player){
			skillAddition = player.getModule(BeautyModule.class).getIdentitySkillAddition(eSkillType.MineOutput.getValue(), 0);
		}else {
			beautyMap = UserBeautyBussiness.getUserBeautyMap(userId);
			skillAddition = SkillMgr.getIdentitySkillAddition(beautyMap, eSkillType.MineOutput.getValue(), 0);
		}
		BigDecimal totalValue = BigDecimal.valueOf(oreAddition);
		double patronsSkillAddition = 0;
		for(UserPatrons userPatrons : patronsList){//计算天赋加成
			for(UserPatronsSkill patronsSkill : userPatrons.getSkillList()){
				if(patronsSkill.getType() != ePatronsSkillType.Talent.getValue()){
					continue;
				}
				SkillInfo skillInfo = SkillMgr.getSkillInfo(patronsSkill.getSkillId());
				if(skillInfo.getType() == eSkillType.MineWarAddOutput.getValue()){
					patronsSkillAddition += SkillMgr.getSkillAddition(skillInfo, patronsSkill.getSkillLv());
				}
			}
		}
		totalValue = totalValue.multiply(BigDecimal.valueOf((patronsSkillAddition + skillAddition + unionAddition) / 1000 + 1)).multiply(BigDecimal.valueOf(patronsList.size())).
				setScale(0, BigDecimal.ROUND_UP);
		return totalValue;
	}
	/**
	 * 抢夺矿坑
	 */
	public OreWarProto.OrePitRobRespMsg.Builder robPit(GamePlayer player, int activityId, int pitId, long pitOwnerUserId, List<Integer> patronsIdList){
		OreWarProto.OrePitRobRespMsg.Builder msg = OreWarProto.OrePitRobRespMsg.newBuilder();
		if(!SystemOpenMgr.systemOpen(player, eSystemId.OreWar.getValue())){
			msg.setRet(GameErrorCode.E_SYSTEM_NO_OPEN);
			return msg;
		}
		if(patronsIdList.size() > GameConfig.MINE_WAR_BATTLE_MAX_PATRONS_COUNT){
			msg.setRet(GameErrorCode.E_ORE_WAR_PATRONS_COUNT_OVER);
			return msg;
		}
		//检测矿坑是否存在
		OrePitInfo pitInfo = orePitInfoMap.get(pitId);
		if(null == pitInfo){
			msg.setRet(GameErrorCode.E_ORE_WAR_ORE_PIT_NO_FOUND);
			return msg;
		}
		UserOrePit userOrePit = userOrePitMap.get(pitId);
		if(null == userOrePit){
			msg.setRet(GameErrorCode.E_ORE_WAR_ORE_PIT_NO_FOUND);
			return msg;
		}
		if(userOrePit.getUserId() == player.getUserId()){
			msg.setRet(GameErrorCode.E_ORE_WAR_ORE_CAN_NO_ROB_SELF_PIT);
			return msg;
		}
		if(userOrePit.getUserId() != pitOwnerUserId){//矿坑占有人发生变化
			msg.setRet(0);
			OreWarProto.OrePitTempMsg.Builder pitMsg = OreWarPb.parseOrePitTempMsg(userOrePit);
			if(null != pitMsg) {
				msg.setOrePit(pitMsg);
			}
			return msg;
		}
		//检测出战门客战斗次数，是否需要发费元宝
		int ret = player.getModule(OreWarModule.class).checkAndCostBattleTimes(patronsIdList,activityId);
		if(0 != ret){
			msg.setRet(ret);
			return msg;
		}

		int occupyCount = player.getModule(OreWarModule.class).getOccupyCount(activityId);
		if(occupyCount >= GameConfig.ACTIVITY_ORE_WAR_OCCUPY_LIMIT){
			msg.setRet(GameErrorCode.E_ORE_WAR_OCCUPY_LIMIT);
			return msg;
		}

		//消耗体力，不够报错
		int useHpRet = player.getModule(OreWarModule.class).useHp(activityId);
		if(useHpRet != 0){
			msg.setRet(useHpRet);
			return msg;
		}

		Property winReward = null;
		BattleResult battleResult;
		synchronized (lockObj) {
			userOrePit = getUserOrePit(pitId);
			//没人占领或者无限坑
			if (userOrePit.getUserId() == 0) {
				//添加通告
//				if(userOrePit.getPitId() < GameConfig.MINE_WAR_NOTICE_NEED_PIT){
				if(getOreStationInfo(userOrePit.getStationId()).isNotice()){
					OreWarNotice oreWarNotice = initOreWarNotice(userOrePit, player.getUserId(), userOrePit.getUserId());
					addOreWarNotice(oreWarNotice);
				}
				winReward = updateOrePitUser(player, userOrePit, patronsIdList);
				msg.setRet(0);
				msg.setWinReward(PropertyHelper.parsePropertyToString(winReward));
				msg.setWinUserId(player.getUserId());
				msg.addAllPatronsIdList(patronsIdList);
				OreWarProto.OrePitTempMsg.Builder pitMsg = OreWarPb.parseOrePitTempMsg(userOrePit);
				if(null != pitMsg){
					msg.setOrePit(pitMsg);
				}
				return msg;
			}
			List<UserPatrons> patronsList = player.getModule(PatronsModule.class).getUserPatronsList(patronsIdList);
			battleResult = BattleManager.battle(player.getUserId(), patronsList, userOrePit.getUserId(), userOrePit.getPatronsList(), 0,
					true, true);

			boolean isWin = false;
			if (battleResult.getWinUserId() == player.getUserId()) {
				isWin = true;
			}
			//添加记录
			OreWarRecord oreWarRecord = initOreWarRecord(userOrePit.getUserId(), userOrePit, isWin, player.getUserId());
			addOreWarRecord(oreWarRecord);

			//添加通告
//			if(userOrePit.getPitId() < GameConfig.MINE_WAR_NOTICE_NEED_PIT && isWin){
			UserInfo origUserInfo = UserMgr.getUserInfo(userOrePit.getUserId());
			if(getOreStationInfo(userOrePit.getStationId()).isNotice() && isWin){
				OreWarNotice oreWarNotice = initOreWarNotice(userOrePit, player.getUserId(), userOrePit.getUserId());
				addOreWarNotice(oreWarNotice);
			}else if((origUserInfo != null && !StringUtils.isNullOrEmpty(origUserInfo.getUnionUid()) && isWin)){
				OreWarNotice oreWarNotice = initOreWarNotice(userOrePit, player.getUserId(), userOrePit.getUserId());
				addOreWarNotice(oreWarNotice);
			}
			// 赢的话 替换阵容
			if (isWin) {
				// 给失败的玩家发送邮件和占领奖励
				UserInfo loserUser = UserMgr.getUserInfo(userOrePit.getUserId());
				String mailTitle = MultipleLanguageMgr.getContent(MailManager.MINE_WAR_BE_ROB_TITLE, loserUser.getLanguage());
				String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.MINE_WAR_BE_ROB_CONTENT, loserUser.getLanguage()),
						getOrePitName(userOrePit.getPitId(), loserUser.getLanguage()), player.getUserInfo().getNickName());
				Property enemyReward = getPitOccupyReward(userOrePit.getUserId(), userOrePit, System.currentTimeMillis() / 1000, true);
				MailManager.sendMail(userOrePit.getUserId(), eMailType.DAILY.getValue(), PropertyHelper.parsePropertyToString(enemyReward), mailContent, mailTitle);

				//被打者领取奖励
				OreWarActivityMgr.conditionNotify(loserUser.getUserId(),eGamePlayerEventType.OreWarAcCoinOutPut.getValue(),
						new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, enemyReward.getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID),
                                loserUser.getUnionUid(), activityInfo.getActivityId()));

				winReward = updateOrePitUser(player, userOrePit, patronsIdList);
				// 同步地块信息
				OreWarProto.OrePitTempMsg.Builder pitMsg = OreWarPb.parseOrePitTempMsg(userOrePit);
				if(null != pitMsg){
					msg.setOrePit(pitMsg);
				}
				msg.setWinUserId(player.getUserId());
			}else {
				msg.setWinUserId(userOrePit.getUserId());
			}
		}
		msg.setRet(0);
		msg.setWinReward(PropertyHelper.parsePropertyToString(winReward));
		//我方信息
		msg.addAllPatronsIdList(patronsIdList);
		//战斗详细信息
		msg.setBattleDetailList(BattlePb.parseBattleDetailListMsg(battleResult.getPatronsBattleDetailList()));
		//对手出战门客、座骑
		for (UserPatrons userPatrons : battleResult.getEnemyPatronsList()) {
			PatronsProto.PatronsTempMsg.Builder patronsMsg = PatronsPb.parsePatronsTempMsg(userPatrons);
			if(null != patronsMsg) {
				msg.addEnemyPatronsList(patronsMsg);
			}
		}
		return msg;
	}
	private void addOreWarRecord(OreWarRecord oreWarRecord) {
		if(null == oreWarRecord){
			return;
		}
		synchronized (oreWarRecordMap) {
			if (!oreWarRecordMap.containsKey(oreWarRecord.getUserId())) {
				oreWarRecordMap.put(oreWarRecord.getUserId(), new ArrayList<>());
			}
		}
		List<OreWarRecord> recordList = oreWarRecordMap.get(oreWarRecord.getUserId());
		synchronized (recordList) {
			if (recordList.size() >= GameConfig.MINE_WAR_MAX_RECORD_COUNT) {
				recordList.remove(0);
			}
			recordList.add(oreWarRecord);
		}
		synchronized (needAddRecordList) {
			needAddRecordList.add(oreWarRecord);
		}
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(oreWarRecord.getUserId());
		if(player != null){
			List<OreWarRecord> syncList = new ArrayList<>();
			syncList.add(oreWarRecord);
			player.sendPacket(Protocol.U_ORE_WAR_RECORD_SYNC, OreWarPb.parseOreWarRecordListMsg(syncList));
		}
	}
	private static OreWarRecord initOreWarRecord(long userId, UserOrePit userOrePit, boolean isWin, long enemyUserId) {
		UserInfo enemyUserInfo = UserMgr.getUserInfo(enemyUserId);
		if(null == enemyUserInfo){
			return null;
		}
		if(null == userOrePit){
			return null;
		}

		OreWarRecord record = new OreWarRecord();
		record.setUserId(userId);
		record.setRecordUid(UUIDHelper.randomUUID(String.valueOf(GameServer.getInstance().getServerId())));
		record.setActivityId(userOrePit.getActivityId());
		record.setPitId(userOrePit.getPitId());
		record.setEnemyUserId(enemyUserId);
		record.setEnemyBaseData(UserMgr.parseUserBaseInfo(enemyUserInfo, GameServer.getInstance().getServerId()));
		record.setRecordTime(System.currentTimeMillis() / 1000);
		record.setWin(isWin);
		return record;
	}

	//返回某个建筑占有多少个坑位
	private int getOrePitCount(int stationId){
		int count = 0;
		for(UserOrePit userOrePit :userOrePitMap.values()){
			if(userOrePit.getStationId() == stationId && userOrePit.getUserId() != 0){
				count++;
			}
		}
		return count;
	}

	//只有抢占的时候用到
	private com.yanqu.road.utils.property.Property updateOrePitUser(GamePlayer player, UserOrePit userOrePit, List<Integer> patronsIdList){
		if(null == player || null == userOrePit || null == patronsIdList){
			return null;
		}
		com.yanqu.road.utils.property.Property reward;
		long oldUserId = userOrePit.getUserId();
		if(oldUserId > 0) {
			UserOreData oldOreData = OreWarMgr.getUserOreData(oldUserId);
			if(null != oldOreData) {
				oldOreData.setTotalBeRobTimes(oldOreData.getTotalBeRobTimes() + 1);
				GamePlayer oldPlayer = GamePlayerMgr.getOnlinePlayer(oldUserId);
				updateOrePitPatronsState(oldPlayer, userOrePit, OreWarMgr.DISPATCH_ORE_NONE);
				if (null != oldPlayer) {
					oldPlayer.getModule(OreWarModule.class).syncOrePit(userOrePit, true);
					//成就、任务
					oldPlayer.notifyListener(eGamePlayerEventType.MineWarTotalBeRobTimes.getValue(), oldOreData);
				}
			}
		}
		long nowTime = System.currentTimeMillis() / 1000;
		userOrePit.setUserId(player.getUserId());
		UserInfo userInfo = UserMgr.getUserInfo(player.getUserId());
		userOrePit.setNickName(userInfo.getNickName());
		userOrePit.setDecoration(UserMgr.getDecoration(userInfo.getUserId()));
		userOrePit.setPatronsIdList(patronsIdList);
		userOrePit.setPatronsList(player.getModule(PatronsModule.class).getUserPatronsList(patronsIdList));
		userOrePit.setJoinTime(nowTime);
		userOrePit.setLastGetRewardTime(nowTime);
		userOrePit.setTotalAbility(player.getModule(PatronsModule.class).getPatronsListAbility(userOrePit.getPatronsIdList()));
		updateOrePitPatronsState(player, userOrePit, OreWarMgr.DISPATCH_ORE_PUBLIC);
		synchronized (needUpdateUserOrePitList) {
			if (!needUpdateUserOrePitList.contains(userOrePit)) {
				needUpdateUserOrePitList.add(userOrePit);
			}
		}
		OreStationInfo stationInfo = getOreStationInfo(userOrePit.getStationId());
		if(null != stationInfo){
			String oldUid = stationInfo.getUnionUid();
			int oldOccupyCount = stationInfo.getOccupyCount();
			changeOreStation(stationInfo);
			//分享卡通知，必须坑位都是满的情况下
			if(stationInfo.getOccupyCount() == stationInfo.getPitCount()){
				if(!stationInfo.getUnionUid().equals(oldUid)){
					WorldMessageProto.WorldMessageTempMsg.Builder chatMsgGet = WorldMessagePb.parseWorldMessageTempMsg(player.getUserInfo(),
							eMessageType.OreWarNamingGet.getValue(), eChatContentType.Common.getContentType(), getOreStationName(stationInfo.getStationId(),player.getLanguage()), System.currentTimeMillis(), 0, null);
					WorldMessageMgr.addWorldMessage(stationInfo.getUnionUid(),chatMsgGet);

					if(!stationInfo.getUnionUid().equals(oldUid)){
						UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(player.getUserInfo().getUnionUid());
						WorldMessageProto.WorldMessageTempMsg.Builder chatMsgLose = WorldMessagePb.parseWorldMessageTempMsg(player.getUserInfo(),
								eMessageType.OreWarNamingLose.getValue(), eChatContentType.Common.getContentType(),
								WorldMessageMgr.encodeContent(unionInfo == null?"":unionInfo.getUnionName(),player.getUserInfo().getNickName(),getOreStationName(stationInfo.getStationId(),player.getLanguage())),
								System.currentTimeMillis(), 0, null);
						WorldMessageMgr.addWorldMessage(oldUid,chatMsgLose);
					}
				}
			}
		}
		//计算占领收益
		reward = getPitOccupyReward(player.getUserId(), userOrePit, nowTime + GameConfig.MINE_WAR_VICTORY_REWARD, false);
		//收益入袋
		player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.OreWar, eLogMoneyType.OreWarWinReward);
		OreWarActivityMgr.conditionNotify(player.getUserId(),eGamePlayerEventType.OreWarAcCoinOutPut.getValue(),
				new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, reward.getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID),
						player.getUserInfo().getUnionUid(), activityInfo.getActivityId()));

		LogMgr.addLogOreWarReward(player.getUserId(), userOrePit.getActivityId(), userOrePit.getPitId(), PropertyHelper.parsePropertyToString(reward),
				GameConfig.MINE_WAR_VICTORY_REWARD, false, eLogMoneyType.OreWarWinReward.getValue());

		//增加累计占领次数
		UserOreData userOreData = player.getModule(OreWarModule.class).getUserOreData();
		userOreData.setTotalRobTimes(userOreData.getTotalRobTimes() + 1);
		//成就、任务
		player.notifyListener(eGamePlayerEventType.MineWarRobTimes.getValue(), 1);
		player.notifyListener(eGamePlayerEventType.MineWarTotalRobTimes.getValue(), userOreData);
		/*if(stationInfo.getPosition() == 1) {//第一个矿位才公告
			if(0 == oldUserId) {
				WorldMessageMgr.worldNotify(eMessageType.MineWarRobPit.getValue(), player.getUserInfo().getCity(), player.getTitleId(),
						player.getUserInfo().getNickName(), userOrePit.getActivityId(), userOrePit.getPitId());
			}else {
				UserInfo oldUserInfo = UserMgr.getUserInfo(oldUserId);
				WorldMessageMgr.worldNotify(eMessageType.MineWarRobPitBattle.getValue(), player.getUserInfo().getCity(), player.getTitleId(),
						player.getUserInfo().getNickName(), oldUserInfo.getCity(), oldUserInfo.getTitleId(), oldUserInfo.getNickName(),
						userOrePit.getActivityId(), userOrePit.getPitId());
			}
		}*/
		player.getModule(OreWarModule.class).syncOrePit(userOrePit, false);
		return reward;
	}

	/**
	 * 领取矿坑占领时间收益
	 */
	public com.yanqu.road.utils.property.Property getPitOccupyReward(long userId, UserOrePit userOrePit, long getRewardTime, boolean isUpdateRewardTime) {
		com.yanqu.road.utils.property.Property occupyReward = new com.yanqu.road.utils.property.Property();
		if(null == userOrePit){
			logger.warn("getPitOccupyReward userOreData is null");
			return occupyReward;
		}
		if(userOrePit.getUserId() != userId){
			logger.warn("getPitOccupyReward userOreData userId not same");
			return occupyReward;
		}
		UserOreData userOreData = OreWarMgr.getUserOreData(userId);
		if(null == userOreData){
			logger.warn("getPitOccupyReward userOreData is null");
			return occupyReward;
		}
		OrePitInfo pitInfo = getOrePitInfo(userOrePit.getPitId());
		long occupyTime = (getRewardTime - userOrePit.getLastGetRewardTime()) / 60;
		if(occupyTime > 0){//算钱咯
			int unionAddition = 0;
			UserInfo userInfo = UserMgr.getUserInfo(userId);
			if(userInfo != null && !StringUtils.isNullOrEmpty(userInfo.getUnionUid()) && oreStationMap.get(userOrePit.getStationId()).getUnionUid().equals(userInfo.getUnionUid())){
				//时间大于当前的时间就是加上了占领奖励时间，不能算商会冠名奖励
				if(getRewardTime <= System.currentTimeMillis()/1000){
					unionAddition = GameConfig.ACTIVITY_ORE_WAR_UNION_NAMING_ADD;
				}
			}
			BigInteger rewardValue = getOreOutput(userId, userOrePit.getPatronsList(), pitInfo.getOutputSpeedAddition(),unionAddition).
					multiply(BigDecimal.valueOf(occupyTime)).toBigInteger();
			GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
			userOreData.setTotalReward1(userOreData.getTotalReward1().add(rewardValue));
			if(rewardValue.compareTo(userOreData.getMaxTeamReward1()) > 0){
				userOreData.setMaxTeamReward1(rewardValue);
				if(null != player){
					player.notifyListener(eGamePlayerEventType.MineWarMaxTeamReward.getValue(), userOreData);
				}
			}
			if(null != player){
				player.notifyListener(eGamePlayerEventType.MineWarTotalReward.getValue(), userOreData);
			}
			int goodsId = GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID;
			if(goodsId > 0){
				occupyReward.addProperty(goodsId, rewardValue);
			}
			if(isUpdateRewardTime) {
				userOrePit.setLastGetRewardTime(getRewardTime);
				synchronized (needUpdateUserOrePitList) {
					if (!needUpdateUserOrePitList.contains(userOrePit)) {
						needUpdateUserOrePitList.add(userOrePit);
					}
				}
			}
		}
		//井喷
		if(userOrePit.isBlowout()){
			occupyReward.rideProperty(BigDecimal.valueOf(GameConfig.ACTIVITY_ORE_WAR_BLOWOUT_ADD).
					divide(BigDecimal.valueOf(1000),3,BigDecimal.ROUND_UP).add(BigDecimal.ONE));
		}
		return occupyReward;
	}

	//把商会冠名和井喷设置上去
	private void setBlowNamingStation(OreStationInfo oreStationInfo){
		//union 0人数 1最后加入时间
		Map<String,List<Integer>> unionSameMap = new ConcurrentHashMap<>();
		List<UserOrePit> tempPitList = getUserOrePitList(oreStationInfo.getStationId());
		oreStationInfo.removeAllUserId();
		for(UserOrePit pit : tempPitList){
			//是否是井喷状态
			if(pit.isBlowout()){
				oreStationInfo.setBlowout(true);
			}else{
				oreStationInfo.setBlowout(false);
			}
			oreStationInfo.addUserId(pit.getUserId());
			UnionMember unionMember = CrossUnionMgr.getUnionMember(pit.getUserId());
			if(unionMember != null){
				if(!unionSameMap.containsKey(unionMember.getUnionUid())){
					unionSameMap.put(unionMember.getUnionUid(),new ArrayList<>());
					unionSameMap.get(unionMember.getUnionUid()).add(0,0);
					unionSameMap.get(unionMember.getUnionUid()).add(1,0);
				}
				unionSameMap.get(unionMember.getUnionUid()).set(0,unionSameMap.get(unionMember.getUnionUid()).get(0) + 1);
				if(pit.getJoinTime() > unionSameMap.get(unionMember.getUnionUid()).get(1)){
					unionSameMap.get(unionMember.getUnionUid()).set(1,unionSameMap.get(unionMember.getUnionUid()).get(1) + 1);
				}
			}
		}
		int lastJoinTime = 0;
		int maxUserCount = 0;
		String maxUnionUid = "";
		//下面是按照人数最多和最后抢占作为冠名
		/*for (String unionUid : unionSameMap.keySet()){
			if(unionSameMap.get(unionUid).get(0) > maxUserCount ||
					(unionSameMap.get(unionUid).get(0) == maxUserCount && unionSameMap.get(unionUid).get(1) > lastJoinTime)){
				maxUserCount = unionSameMap.get(unionUid).get(0);
				lastJoinTime = unionSameMap.get(unionUid).get(1);
				maxUnionUid = unionUid;
			}
		}*/
		int maxSameCount = 1;
		for (String unionUid : unionSameMap.keySet()){
			if(unionSameMap.get(unionUid).get(0) > maxUserCount){
				maxUserCount = unionSameMap.get(unionUid).get(0);
				maxUnionUid = unionUid;
				maxSameCount = 1;
			}else if(unionSameMap.get(unionUid).get(0) == maxUserCount){
				maxSameCount++;
			}
		}
		if(maxSameCount != 1){
			maxUnionUid = "";
		}
		//发送冠名变化奖励
		sendUnionNamingChangeReward(oreStationInfo.getStationId(),oreStationInfo.getUnionUid(),maxUnionUid);
		oreStationInfo.setUnionUid("");
		oreStationInfo.setUnionName("");
		oreStationInfo.setUnionCount(0);
		oreStationInfo.setLastJoinTime(0);
		UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(maxUnionUid);
		if(unionInfo != null){
			oreStationInfo.setUnionUid(unionInfo.getUnionUid());
			oreStationInfo.setUnionName(unionInfo.getUnionName());
			oreStationInfo.setUnionCount(maxUserCount);
			oreStationInfo.setLastJoinTime(lastJoinTime);
		}
		for(UserOrePit pit : tempPitList){
			UnionMember unionMember = CrossUnionMgr.getUnionMember(pit.getUserId());
			if(unionMember != null && !StringUtils.isNullOrEmpty(unionMember.getUnionUid()) && unionMember.getUnionUid().equals(oreStationInfo.getUnionUid())){
				pit.setNaming(true);
			}else{
				pit.setNaming(false);
			}
			syncOnlineUserOrePit(pit);
		}
	}

	private void syncOnlineUserOrePit(UserOrePit userOrePit){
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userOrePit.getUserId());
		if(null != player){
			//同步自己占领的坑位信息给自己
			player.getModule(OreWarModule.class).syncOrePit(userOrePit, false);
		}
	}

	//判断新老商会id来判断冠名是否发生变化了
	private void sendUnionNamingChangeReward(int stationId,String oldUid,String newUid){
		//之前有商会冠名着，被打下来了，要给他结算冠名奖励
		if(!isReload && !StringUtils.isNullOrEmpty(oldUid) && !oldUid.equals(newUid)){
			sendNamingChangeReward(stationId,oldUid);
		}
		//打出冠名的商会的商会成员要把之前的结算了，然后开始计时冠名奖励
		if(!isReload && !StringUtils.isNullOrEmpty(newUid) && !oldUid.equals(newUid)){
			sendNamingChangeReward(stationId,newUid);
		}
	}

	/**
	 * //坑位的冠名发送了变化，涉及到奖励的两个家族或一个家族发放奖励
	 * @param stationId
	 * @param unionUid  获得冠名或者失去冠名的家族
	 */
	public void sendNamingChangeReward(int stationId,String unionUid){
		Map<Long,Property> userRewardMap = new ConcurrentHashMap<>();
		for(UserOrePit userOrePit : userOrePitMap.values()){
			if(userOrePit.getStationId() == stationId){
				UserInfo userInfo = UserMgr.getUserInfo(userOrePit.getUserId());
				if(userInfo != null && unionUid.equals(userInfo.getUnionUid())){
					if(!userRewardMap.containsKey(userOrePit.getUserId())){
						userRewardMap.put(userOrePit.getUserId(),new Property());
					}
					Property reward = getPitOccupyReward(userOrePit.getUserId(), userOrePit, System.currentTimeMillis()/1000, true);
					userRewardMap.get(userOrePit.getUserId()).addProperty(reward);
					//同步坑位的领奖信息给客户端
					GamePlayer player = GamePlayerMgr.getOnlinePlayer(userOrePit.getUserId());
					if(player != null){
						player.getModule(OreWarModule.class).syncOrePit(userOrePit, false);
					}
				}
			}
		}
		for(long userId : userRewardMap.keySet()){
			Property namingReward = userRewardMap.get(userId);
			if(!namingReward.isNothing()){
				sendNamingReward(userId,stationId,namingReward);
			}
		}
	}

	//商会解散的时候这个商会要是是冠名状态要结算
	public void sendUnionDismissNamingChangeReward(String unionUid){
		if(StringUtils.isNullOrEmpty(unionUid)){
			return;
		}
		Map<Long,Map<Integer,Property>> userRewardMap = new ConcurrentHashMap<>();
		for(UserOrePit userOrePit : userOrePitMap.values()){
			String stationUid = oreStationMap.get(userOrePit.getStationId()).getUnionUid();
			if(stationUid.equals(unionUid)){
				if(!userRewardMap.containsKey(userOrePit.getUserId())){
					userRewardMap.put(userOrePit.getUserId(),new ConcurrentHashMap<>());
				}
				if(!userRewardMap.get(userOrePit.getUserId()).containsKey(userOrePit.getStationId())){
					userRewardMap.get(userOrePit.getUserId()).put(userOrePit.getStationId(),new Property());
				}
				Property reward = getPitOccupyReward(userOrePit.getUserId(), userOrePit, System.currentTimeMillis()/1000, true);
				userRewardMap.get(userOrePit.getUserId()).get(userOrePit.getStationId()).addProperty(reward);
				//同步坑位的领奖信息给客户端
				GamePlayer player = GamePlayerMgr.getOnlinePlayer(userOrePit.getUserId());
				if(player != null){
					player.getModule(OreWarModule.class).syncOrePit(userOrePit, false);
				}
			}
		}
		for(long userId : userRewardMap.keySet()){
			for(int stationId : userRewardMap.get(userId).keySet()){
				Property namingReward = userRewardMap.get(userId).get(stationId);
				if(!namingReward.isNothing()){
					sendNamingReward(userId,stationId,namingReward);
				}
			}
		}
	}

	//用户被踢出商会或者自己退出或者加入商会要判断他的坑位所在的建筑是不是冠名状态，是的话发送奖励
	public void sendUnionNamingJoinQuitReward(String unionUid, long userId){
		if(StringUtils.isNullOrEmpty(unionUid)){
			return;
		}
		Map<Integer,Property> userRewardMap = new ConcurrentHashMap<>();
		List<UserOrePit> userOrePitList = getUserOrePitList(userId);
		for(UserOrePit userOrePit : userOrePitList){
			String stationUid = oreStationMap.get(userOrePit.getStationId()).getUnionUid();
			if(stationUid.equals(unionUid)){
				if(!userRewardMap.containsKey(userOrePit.getStationId())){
					userRewardMap.put(userOrePit.getStationId(),new Property());
				}
				Property reward = getPitOccupyReward(userOrePit.getUserId(), userOrePit, System.currentTimeMillis()/1000, true);
				userRewardMap.get(userOrePit.getStationId()).addProperty(reward);
				//同步坑位的领奖信息给客户端
				GamePlayer player = GamePlayerMgr.getOnlinePlayer(userOrePit.getUserId());
				if(player != null){
					player.getModule(OreWarModule.class).syncOrePit(userOrePit, false);
				}
			}
		}
		for(int stationId : userRewardMap.keySet()){
			Property namingReward = userRewardMap.get(stationId);
			if(!namingReward.isNothing()){
				sendNamingReward(userId,stationId,namingReward);
			}
		}
	}

	//发送冠名变化的奖励
	public void sendNamingReward(long userId,int stationId,Property reward){
		// 冠名变化的玩家发奖励
		UserInfo namingUser = UserMgr.getUserInfo(userId);
		String mailTitle = MultipleLanguageMgr.getContent(MailManager.ACTIVITY_ORE_WAR_NAMING_CHANGE_TITLE, namingUser.getLanguage());
		String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.ACTIVITY_ORE_WAR_NAMING_CHANGE_CONTENT, namingUser.getLanguage())
				,getOreStationName(stationId,namingUser.getLanguage()));
		MailManager.sendMail(userId, eMailType.DAILY.getValue(), PropertyHelper.parsePropertyToString(reward), mailContent, mailTitle);

		OreWarActivityMgr.conditionNotify(userId,eGamePlayerEventType.OreWarAcCoinOutPut.getValue(),
				new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, reward.getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID),
						namingUser.getUnionUid(), activityInfo.getActivityId()));
	}

	//更改占领人数
	public void changeOreStation(OreStationInfo oreStationInfo) {
		List<UserOrePit> tempPitList = getUserOrePitList(oreStationInfo.getStationId());
		BigInteger totalAbility = BigInteger.ZERO;
		int occupyCount = 0;
		for(UserOrePit pit : tempPitList){
			if(pit.getUserId() != 0){
				occupyCount++;
				if(oreStationInfo.isShowAbility()) {
					totalAbility = totalAbility.add(pit.getTotalAbility());
				}
			}
		}
		oreStationInfo.setOccupyCount(occupyCount);
		if(oreStationInfo.isShowAbility() && occupyCount >= GameConfig.MINE_WAR_OCCUPY_PIT_COUNT_SHOW_ABILITY){
			oreStationInfo.setAverageAbility(totalAbility.divide(BigInteger.valueOf(occupyCount)));
		}else {
			oreStationInfo.setAverageAbility(BigInteger.ZERO);
		}
		setBlowNamingStation(oreStationInfo);
	}

	//根据用户盐场坑位撤回玩家门客占领数据
	private static void updateOrePitPatronsState(GamePlayer player, UserOrePit userOrePit, int dispatchOre){
		int activityId = userOrePit.getActivityId();
		int pitId = 0;
		if(dispatchOre > 0){
			pitId = userOrePit.getPitId();
		}
		if(null != player){
			player.getModule(OreWarModule.class).updateOrePitPatronsState(userOrePit.getPatronsIdList(), dispatchOre, activityId, pitId);
		}else {//通过修改数据库修改状态
			UserOreWarBussiness.updateUserOreWarPatronsData(userOrePit.getUserId(), userOrePit.getPatronsIdList(), dispatchOre, activityId, pitId);
		}
	}
	//根据玩家广场坑位撤回玩家门客占领数据
	private static void updateOreRefugePatronsState(GamePlayer player, UserOreRefuge userOreRefuge, int dispatchOre){
		int activityId = userOreRefuge.getActivityId();
		int pitId = 0;
		if(dispatchOre > 0){
			pitId = userOreRefuge.getPitId();
		}
		if(null != player){
			player.getModule(OreWarModule.class).updateOrePitPatronsState(userOreRefuge.getPatronsIdList(), dispatchOre, activityId, pitId);
		}else {//通过修改数据库修改状态
			UserOreWarBussiness.updateUserOreWarPatronsData(userOreRefuge.getUserId(), userOreRefuge.getPatronsIdList(), dispatchOre, activityId, pitId);
		}
	}

	private void addOreWarNotice(OreWarNotice notice) {
		if(null == notice){
			return;
		}
		synchronized (oreWarNoticeList) {
			if(oreWarNoticeList.size() >= GameConfig.MINE_WAR_MAX_NOTICE_COUNT){
				oreWarNoticeList.removeFirst();
			}
			oreWarNoticeList.addLast(notice);
			needAddNoticeList.add(notice);
		}
	}

	private static OreWarNotice initOreWarNotice(UserOrePit userOrePit, long userId, long enemyUserId){
		if(null == userOrePit || userId <= 0){
			return null;
		}
		UserInfo userInfo = UserMgr.getUserInfo(userId);
		if(null == userInfo){
			return null;
		}
		UserInfo enemyUserInfo = null;
		if(enemyUserId > 0) {
			enemyUserInfo = UserMgr.getUserInfo(enemyUserId);
			if (null == enemyUserInfo) {
				return null;
			}
		}
		OreWarNotice oreWarNotice = new OreWarNotice();
		oreWarNotice.setNoticeUid(UUIDHelper.randomUUID(String.valueOf(GameServer.getInstance().getServerId())));
		oreWarNotice.setActivityId(userOrePit.getActivityId());
		oreWarNotice.setPitId(userOrePit.getPitId());
		oreWarNotice.setNoticeTime(System.currentTimeMillis() / 1000);
		oreWarNotice.setUserId(userInfo.getUserId());
		oreWarNotice.setUserBaseInfo(UserMgr.parseUserBaseInfo(userInfo, GameServer.getInstance().getServerId()));
		if(null == enemyUserInfo){
			oreWarNotice.setEnemyUserId(0);
			oreWarNotice.setEnemyBaseInfo(new UserBaseInfo());
		}else {
			oreWarNotice.setEnemyUserId(enemyUserInfo.getUserId());
			oreWarNotice.setEnemyBaseInfo(UserMgr.parseUserBaseInfo(enemyUserInfo, GameServer.getInstance().getServerId()));
		}
		return oreWarNotice;
	}

	//任务执行
	public void addTask(GeneralTask task) {
		threadTaskManger.addTask(actionId.getAndIncrement(), task);
	}

	//获取系统撤回避难所的所有应该获得奖励
	private Property getRefugeSystemRecallAll(long userId,long nowTimeMilli) {
		Property reward = new Property();
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
		if(player != null){
			reward = player.getModule(OreWarModule.class).refugeRecallAll(activityInfo.getActivityId());
		}else{
			List<UserOreRefuge> needUpdate = new ArrayList<>();
			Map<Integer, UserOreRefuge> userOreRefugeMap = UserOreWarBussiness.getUserOreRefugeMap(userId,activityInfo.getActivityId());
			for(UserOreRefuge userOreRefuge : userOreRefugeMap.values()){
				if(userOreRefuge.getPatronsIdList() != null && userOreRefuge.getPatronsIdList().size() > 0){
					long nowTime = nowTimeMilli / 1000;
					long occupyTime = (nowTime - userOreRefuge.getLastGetRewardTime()) / 60;
					long lastGetRewardTime = userOreRefuge.getLastGetRewardTime();
					Map<Integer,UserPatrons> patronsMap = UserPatronsBussiness.getUserPatronsMap(userId,userOreRefuge.getPatronsIdList());
					BigInteger oreOutput = getOreOutput(userId,new ArrayList<>(patronsMap.values()), GameConfig.ACTIVITY_ORE_WAR_SQUARE_PROFIT,0).multiply(BigDecimal.valueOf(occupyTime)).toBigInteger();
					reward.addProperty(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID, oreOutput);
					updateOreRefugePatronsState(player,userOreRefuge, OreWarMgr.DISPATCH_ORE_NONE);
					userOreRefuge.setLastGetRewardTime(nowTime);
					userOreRefuge.setPatronsIdList(new ArrayList<>());
					needUpdate.add(userOreRefuge);
					LogMgr.addLogOreWarReward(userId, userOreRefuge.getActivityId(), userOreRefuge.getPitId(), PropertyHelper.parsePropertyToString(reward),
							nowTime - lastGetRewardTime, true, eLogMoneyType.OreWarRefugeRecall.getValue());
				}

			}
			UserOreWarBussiness.updateUserOreRefugeList(needUpdate);
		}
		return reward;
	}
}
